<template>
    <div id="add-edit-job-application">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="50%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('kJu7Trhi2W73OAVloSf')" prop="v_ProjectName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_ProjectName" 
                                filterable 
                                class="m-2" 
                                value-key="n_Id"
                                :placeholder="$t('bxEXZmbbz9Az6kHFzoId')" 
                                @change="projectChange"
                            >
                                <el-option
                                    v-for="item in projectOption"
                                    :key="item.n_Id"
                                    :label="item.v_ItemProjectName"
                                    :value="item.n_Id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('0EDVq0EaoQowa5yp4H0')" prop="d_JobTime" :label-width="formLabelWidth">
                            <el-date-picker
                                class="set-t"
                                v-model="ruleForm.d_JobTime"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :placeholder="$t('xYKtSx361Hm1x9r3giOx')"
                                popper-class="el-date-p"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('0EDVq0EaoQowa5yp4H1')" prop="D_IntendedCompletionTime" :label-width="formLabelWidth">
                            <el-date-picker
                                class="set-t"
                                v-model="ruleForm.D_IntendedCompletionTime"
                                type="datetime"
                                value-format="YYYY-MM-DD"
                                :placeholder="$t('cy39RiPlIRgEr668ssArZ')"
                                popper-class="el-date-p"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('xuuQbgKgXbSnhNsF78bC')" prop="v_JobAddress" :label-width="formLabelWidth">
                            <el-input v-model="ruleForm.v_JobAddress" :placeholder="$t('xuuQbgKgXbSnhNsF78bC')" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('qVn0337gWLy0M0qCFzJ')" prop="value" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.value" 
                                filterable 
                                class="m-2" 
                                value-key="id"
                                :placeholder="$t('qVn0337gWLy0M0qCFzJ')" 
                                @change="valueChange"
                            >
                                <el-option
                                    v-for="item in valueOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="申请人" prop="name" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.name" 
                                filterable 
                                class="m-2" 
                                value-key="id"
                                placeholder="选择申请人" 
                                @change="useChange"
                            >
                                <el-option
                                    v-for="item in useOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> -->

                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('kLRAh7kSOpCR43p3hr')" prop="v_WorkExplain" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_WorkExplain" 
                                filterable 
                                class="m-2" 
                                value-key="n_Id"
                                :placeholder="$t('mEj5wDmCZsCfxTRosWxRj')" 
                                @change="WorkTypeChange"
                            >
                                <el-option
                                    v-for="item in WorkTypeOption"
                                    :key="item.n_Id"
                                    :label="item.v_WorkExplain"
                                    :value="item.n_Id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> -->

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('sXyZ6PqmWwEIov0bNsb')" prop="auditEmp" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.auditEmp" 
                                filterable 
                                multiple
                                collapse-tags
                                class="m-2" 
                                value-key="id"
                                :placeholder="$t('sXyZ6PqmWwEIov0bNsb')" 
                                @change="auditChange"
                            >
                                <el-option
                                    v-for="item in auditOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('fG0nvZkXayViOtkv4mYpi')" :label-width="formLabelWidth">
                            <upload-file
                                :fileName="$t('hirO5pqIqMajwZyQonNs')"
                                :isCancel="isCancel"
                                @fileArr="fileArrFun"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('sfwbsExMM3lGjDuN5zHf')" :label-width="formLabelWidth">
                            <el-switch
                                v-model="ruleForm.n_isValid"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                :active-text="$t('iPfonvtxVLm7knSyCsLBo')"
                                :inactive-text="$t('tzm8JwYsKnqKoNhheJlJx')"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('znlr2HhiXheU4cdB8JdS4')" prop="v_ApplyContent" :label-width="formLabelWidth">
                            <el-input type="textarea" v-model="ruleForm.v_ApplyContent" :placeholder="$t('znlr2HhiXheU4cdB8JdS4')" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('9RLaVEiJf1Z1Qv15o6Kll')" :label-width="formLabelWidth">
                            <el-input type="textarea" v-model="ruleForm.v_Remake" :placeholder="$t('9RLaVEiJf1Z1Qv15o6Kll')" clearable />
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('yk_2HiWXbUkfQ7F6e3kXw') }}</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('zdZCl09qrTjuPhYzWz7L') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , Ref , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules , ElMessage } from 'element-plus'
import { 
    sysDictDataList , 
    sysUserSelector , 
    HazardGetHazardList , 
    JobApplyAddJob , 
    projectitemSelector ,
    sysFileInfoMultipleUploads ,
    AttendanceRecordGenerateId ,
} from '/@/api/sms/sms'
import UploadFile from '../../components/upload-file.vue'
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    n_Id?: Number, // 主键N_Id

    auditEmp: String, // 审核人员 

    jobFile: String, // 作业附件

    n_ProjectId: Number, // 项目Id
    v_ProjectName: String, // 项目名称（用于显示）

    // n_HazardId: Number, // 危险源Id
    // v_WorkExplain: String, // 危险源类别（用于显示）

    n_FileId: Number, // 文件Id

    n_JobTypeId: Number, // 申请作业类型Id
    value: String, // 申请作业类型(用于显示)

    // n_ApplyEmp: Number, // 申请人员id
    // name: String, // 申请人员名称（用于显示）

    d_JobTime: String, // 动工时间
    D_IntendedCompletionTime: String, // 计划完成日期
    v_JobAddress: String, //动工地点
    v_ApplyContent: String, // 申请内容

    n_isValid: Boolean, // 是否启用 1启用/2禁用
    v_Remake: String, // 详情/备注
}
export default defineComponent( {
    name: 'add-edit-job-application',
    components: { UploadFile },
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const { proxy } = useCurrentInstance();
        const $t = proxy.$t;
        
        const titleCon = ref()
        const ruleFormRef = ref()

        const useOption = ref()
        const projectOption = ref()
        const WorkTypeOption = ref()
        const valueOption = ref()
        const auditOption = ref()

        // 多文件上传定义信息
        const isCancel = ref(false)
        let snowflakeId: any = 0
        let fileArrList:any = []
        // 多文件上传定义信息

        // ===============多文件上传封装方法===========

        /*** getNeedId 获取雪花id */
        const getNeedId = async () => {
            let res:any = await AttendanceRecordGenerateId()
            if(res.success) snowflakeId = res.data
        }

        /***  fileArrFun 文件上传数据回传 */
        const fileArrFun = (arr:any) => {
            fileArrList = arr
        }
        /*** fileInfoFun 处理文件格式 */
        const fileInfoFun = (file: any) => {
            let fileArr:any = []
            if(file.length !== 0){
                file.map((i:any) => {
                    fileArr.push(i.raw)
                })
            }
            return fileArr
        }
        /*** uploadFileFuns 多文件上传无返回提示 */
        const uploadFileFuns = async (file: any , xhId: Number) => {
            let param:any = {}
            param.files = file
            param.sourceType = 'SMS'
            param.sourceId = xhId
            let res:any = await sysFileInfoMultipleUploads(param)
            if(res.success) return
        }
        // ===============多文件上传封装方法===========

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 审核人员
            auditEmp: [
				{ required: true, message: $t('xHpgMkEcXnE3D8_1Wmw'), trigger: 'blur' },
			],
            // 危险源
            v_WorkExplain: [
				{ required: true, message: $t('zxGaloajaAo1yMttcTunx'), trigger: 'change' },
			],
            // 作业类型
            value: [
				{ required: true, message: $t('hscN8Y3xWzf7iS7adyMyw'), trigger: 'change' },
			],
            // 申请人员
            name: [
				{ required: true, message: $t('bM56AdFr3vtKKovvPeu'), trigger: 'change' },
			],
            // 动工时间
            d_JobTime: [
				{ required: true, message: $t('gnrQb1f2ru3E8SgU3cCfZ'), trigger: 'change' },
			],
            // 计划完成日期
            D_IntendedCompletionTime: [
				{ required: true, message: $t('cy39RiPlIRgEr668ssArZ'), trigger: 'change' },
			],
            // 动工地点
            v_JobAddress: [
				{ required: true, message: $t('cOnrMhKw9p6gV71Ls5Puw'), trigger: 'blur' },
			],
            // 申请内容
            v_ApplyContent: [
				{ required: true, message: $t('s3GFsWs5Tlb5UtNLu6nqn'), trigger: 'blur' },
			],
            // 作业附件
            jobFile: [
				{ required: true, message: $t('adxOitHyRbNmgMhZ8J628'), trigger: 'blur' },
			],
            // 项目名称
            v_ProjectName: [
                { required: true, message: $t('kJu7Trhi2W73OAVloSf'), trigger: 'change' },
            ],
        })

        /*** projectChange 项目选择下拉框 */
        const projectChange = (val:any) => {
            state.ruleForm.n_ProjectId = val
        }

        /*** WorkTypeChange 危险源选择下拉框 */
        const WorkTypeChange = (val:any) => {
            // console.log(val,'危险源数据')
            // state.ruleForm.n_HazardId = val
        }

        /*** valueChange 作业类型下拉选择事件 */
        const valueChange = (val:any) => {
            state.ruleForm.n_JobTypeId = val
        }

        /*** auditChange 审核人下拉框事件 */
        const auditChange = (val:any) => {
            // console.log(val,'审核人数据')
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick()
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            cleanFile()
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let getData = toRaw(state.ruleForm)
                    let param:any = {}
                    getData.n_isValid ? param.n_isValid = 1 : param.n_isValid = 2
                    param.auditEmp = getData.auditEmp.toString()
                    const {n_isValid , v_ProjectName , value , ...getArr} = getData
                    let valObj = {...getArr,...param}

                    // 文件上传
                    if(fileArrList.length !== 0){
                        let arr = fileInfoFun(fileArrList)
                        uploadFileFuns(arr, snowflakeId)
                    }
                    // 文件上传
                    
                    if(props.repairInfo === ''){
                        state.repeatDis = true
                        valObj.n_FileId = snowflakeId
                        let res:any = await JobApplyAddJob(valObj)
                        if(res.success){
                            ctx.emit('updateData')
                            ctx.emit('controlUseClick')
                            cleanFile()
                            state.repeatDis = false
                        }
                    }else{
                        console.log('编辑')
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
            cleanFile()
        }

        /*** cleanFile 清空文件数据 */
        const cleanFile = () => {
            isCancel.value = true
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false
                isCancel.value = false
                if(props.repairInfo !== ''){
                    titleCon.value = $t('qdjaUu5q3JYq0bnq8l')
                }else{
                    titleCon.value = $t('kfR7oKqGr0sNpRoAhHcM')
                    state.ruleForm.auditEmp = '' // 审核人员 
                    state.ruleForm.jobFile = '' // 作业附件
                    state.ruleForm.n_ProjectId = 0 // 项目Id
                    state.ruleForm.v_ProjectName = '', // 项目名称

                    // state.ruleForm.n_HazardId = 0 // 危险源Id
                    // state.ruleForm.v_WorkExplain = '', // 危险源类别（用于显示）

                    state.ruleForm.n_FileId = 0 // 文件Id
                    state.ruleForm.n_JobTypeId = 0 // 申请作业类型Id
                    state.ruleForm.value = '', // 申请作业类型(用于显示)

                    state.ruleForm.d_JobTime = '' // 动工时间
                    state.ruleForm.D_IntendedCompletionTime = '' // 计划完成日期
                    state.ruleForm.v_JobAddress = '' //动工地点
                    state.ruleForm.v_ApplyContent = '' // 申请内容

                    // state.ruleForm.n_ApplyEmp = 0 // 申请人员
                    // state.ruleForm.name = '', // 申请人员名称（用于显示）

                    state.ruleForm.n_isValid = true // 是否启用 1启用/2禁用
                    state.ruleForm.v_Remake = '' // 详情/备注
                    getNeedId()
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        onMounted(() => {
            GetInfo()
        })

        /*** GetInfo 获取所有信息 */
        const GetInfo = async () => {
            // 作业类型
            let res:any = await sysDictDataList({ typeCode: 'job_Apply' })

            // 用户列表
            let useRes:any = await sysUserSelector()

            // 危险源列表
            let hazarRes:any = await HazardGetHazardList()

            // 项目列表
            let projectRes:any = await projectitemSelector()


            if(res.success){
                valueOption.value = res.data
            }
            if(useRes.success){
                useOption.value = useRes.data
                auditOption.value = useRes.data
            }
            if(hazarRes.success){
                let setArr:any = []
                hazarRes.data.map((i:any) => {
                    for(let z in i.levels){
                        setArr.push(i.levels[z])
                    }
                })
                WorkTypeOption.value = setArr
            }
            if(projectRes.success){
                projectOption.value = projectRes.data
            }
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            formLabelWidth: '120px',
            // useChange,
            useOption,
            projectChange,
            projectOption,
            WorkTypeChange,
            WorkTypeOption,
            valueChange,
            valueOption,

            auditChange,
            auditOption,

            // 多文件上传方法
            fileArrFun,
            isCancel,
            // 多文件上传方法
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%!important;
    }
    :deep(.el-upload){
        width: 100%!important;
    }
    .set-t{
        width: 100%!important;
    }
    .upload-d{
        position: relative;
        width: 100%;
        :deep(.el-upload){
            width: 100%;
            // position: absolute;
            // top: 0;
            // left: 0;
        }
        .upload-b{
            display: flex;
            align-items: center;
            position: absolute;
            top: 8px;
            right: 10px;
            line-height: initial;
            background: unset !important;
            :deep(a){
                background: unset !important;
                margin-right: 10px;
            }
            :deep(span){
                background: unset !important;
            }
        }
    }
</style>